﻿using System.IO;
using System.Net;
using System.Text;

namespace WaterDrop.Controllers
{
    public class HttpHelper
    {
        public static string SendRequest(string data, string requestUrl)
        {
            return SendRequest(Encoding.GetEncoding("UTF-8").GetBytes(data), requestUrl);
        }

        public static string SendRequest(byte[] data, string requestUrl)
        {
            string htmlStr = string.Empty;

            //创建一个客户端的Http请求实例
            HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
            request.ContentType = "application/json";
            request.Method = "POST";
            request.ContentLength = data.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(data, 0, data.Length);
            requestStream.Close();

            //获取当前Http请求的响应实例
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            Stream responseStream = response.GetResponseStream();
            using (StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("UTF-8")))
            {
                htmlStr = reader.ReadToEnd();
            }
            responseStream.Close();

            return htmlStr;
        }

        public static string GetRequest(string requestUrl)
        {
            string htmlStr = string.Empty;

            //创建一个客户端的Http请求实例
            HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "GET";

            //获取当前Http请求的响应实例
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            Stream responseStream = response.GetResponseStream();
            using (StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("UTF-8")))
            {
                htmlStr = reader.ReadToEnd();
            }
            responseStream.Close();

            return htmlStr;
        }
    }
}
 